import fs from 'fs';
import os from 'os';
import path from 'path';
import {FileUtil} from './FileUtil.js';

const CONFIG_DIR_NAME = '.cc';
const CONFIG_FILE_NAME = 'settings.json';

const DEFAULT_SETTINGS = {
    profiles: {}
};

function cloneDefaultSettings() {
    return JSON.parse(JSON.stringify(DEFAULT_SETTINGS));
}

export class CcSettings {
    constructor(logger) {
        this.logger = logger;
        this.configDir = path.join(os.homedir(), CONFIG_DIR_NAME);
        this.configFile = path.join(this.configDir, CONFIG_FILE_NAME);
    }

    load() {
        try {
            if (!fs.existsSync(this.configFile)) {
                return cloneDefaultSettings();
            }
            const raw = fs.readFileSync(this.configFile, 'utf8');
            if (!raw.trim()) {
                return cloneDefaultSettings();
            }
            const parsed = JSON.parse(raw);
            return this.ensureStructure(parsed);
        } catch (error) {
            this.logger?.warn?.(`读取 cc 配置失败，将使用默认配置: ${error.message}`);
            return cloneDefaultSettings();
        }
    }

    save(settings) {
        const payload = this.ensureStructure(settings);
        FileUtil.ensureDir(this.configDir);
        fs.writeFileSync(this.configFile, JSON.stringify(payload, null, 4), 'utf8');
    }

    ensureStructure(settings) {
        if (!settings || typeof settings !== 'object' || Array.isArray(settings)) {
            return cloneDefaultSettings();
        }
        if (!settings.profiles || typeof settings.profiles !== 'object' || Array.isArray(settings.profiles)) {
            settings.profiles = {};
        }
        return settings;
    }

    listProfiles() {
        const {profiles} = this.load();
        return Object.entries(profiles || {})
            .sort((a, b) => a[0].localeCompare(b[0], 'zh-Hans-CN'));
    }

    getProfile(name) {
        if (!name) {
            return null;
        }
        const normalized = name.trim();
        if (!normalized) {
            return null;
        }
        const {profiles} = this.load();
        return profiles?.[normalized] ?? null;
    }

    addProfile(name, baseUrl, token) {
        const normalized = name?.trim();
        if (!normalized) {
            const error = new Error('配置名称不能为空');
            error.code = 'INVALID_NAME';
            throw error;
        }
        const payload = this.load();
        if (payload.profiles[normalized]) {
            const error = new Error(`配置 ${normalized} 已存在`);
            error.code = 'DUPLICATE_PROFILE';
            throw error;
        }
        payload.profiles[normalized] = {
            baseUrl: baseUrl?.trim() ?? '',
            token: token?.trim() ?? '',
            updatedAt: new Date().toISOString()
        };
        this.save(payload);
        return payload.profiles[normalized];
    }
}
